package binary_tree.leetcode.easy;

import java.util.HashMap;
import java.util.Map;

/**
 * @author bruin_du
 * @description 平衡二叉树
 * @date 2022/5/31 16:57
 **/
public class Offer52_IsBalanced {
    boolean res = true;
    public boolean isBalanced(TreeNode root) {
        //方法一: 在进入时剪枝
//        if (root == null) return true;
//        method1(root);
//        return res;

        //方法二:剪枝
        return method2(root) != -1;
    }

    private int method1(TreeNode root) {
        if (root == null || !res) return 0;
        int left = method1(root.left);
        int right = method1(root.right);
        if (Math.abs(left - right) > 1) res = false;
        return Math.max(left, right) + 1;
    }

    private int method2(TreeNode root) {
        if(root == null) return 0;
        int left = method2(root.left);
        if(left == -1) return -1;
        int right = method2(root.right);
        if(right == -1) return -1;
        return Math.abs(left - right) < 2 ? Math.max(left,right) + 1 : -1;
    }
}
